var express = require('express');
var router = express.Router();
const { secretKey, sha256 } = require('../utils/token')
const jwt = require("jsonwebtoken")
var adminService = require('../service/adminService')



// 登录
router.post('/login', async function (req, res, next) {
  let { account, password } = req.body
  console.log(req.body,"req.body");
  let data = await adminService.login(account, sha256(password))
  console.log(data);
  if (Object.keys(data).length > 0) {
    // req.session.user = data;
    // 生成token
    let authToken = jwt.sign({ user: data }, secretKey);
    // 将生成的token返回
    console.log(authToken,"authToken");
    res.send({ token: authToken,data });
    return
  }
  res.send(data)
});


// 注册 增加
router.post('/register', async function (req, res, next) {
  let adminUser = req.body
  adminUser["isBan"] = false
  adminUser.password = sha256(adminUser.password)
  let data = await adminService.register(adminUser)
  res.send(data);
});

// 查找所有 分页
router.get('/find', async function (req, res, next) {
  console.log(12345);
  let { type, value, current, size, flag, position } = req.query;
  let searchObj = {
    position
  };
  // 模糊查询
  if (type && value) {
    if (type == 'status' || type == 'position' || flag) {
      searchObj[type] = value;
    } else {
      searchObj[type] = { $regex: value };
    }
  }
  let data = await adminService.findAdminUser(searchObj, { current: current || 1, size: size || 3 })
  res.send(data);
});

// 修改
router.put('/update/:id', async function (req, res, next) {
  let id = req.params.id;
  let data = await adminService.update(id, req.body)
  res.send(data);
});

//删除
router.delete('/:id', async function (req, res) {
  let id = req.params.id
  let data = await adminService.delete(id)
  res.send(data)
})

//根据ID查询
router.get('/:id', async function (req, res, next) {
  let id = req.params.id;
  console.log(id)
  let data = await adminService.findById(id);
  console.log(data)
  res.send(data);
})

//查询所有 不分页
router.get('/', async function (req, res, next) {
  console.log("查所有");
  let data = await adminService.findUserAll()
  res.send(data);
});
module.exports = router;
